package com.my.socket.nio.v19;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class Server implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public Server(String host, int port) throws Exception {
        this.selector = Selector.open();

        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                int select = this.selector.select();
                LOGGER.info("{} event(s) incoming......", select);

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(this.selector, SelectionKey.OP_READ);
                        LOGGER.info("incoming socket channel: {}, total connections: {}", socketChannel, ++count);
                    } else if (selectionKey.isReadable()) {
                        /**
                         * 关闭客户端，服务端会发生一个read事件，并且在read的时候抛出异常，来表示关闭
                         * 这个事件会不断发生，就算从已准备好的集合移除也没有，必须将该channel关闭或者调用哪个该key的cancel方法
                         *
                         * 因为SelectionKey代表的是Selector和Channel之间的联系，所以在Channel关闭了之后，对于Selector来说，这个Channel永远都会发出关闭这个事件，表明自己关闭了，直到从该Selector移除去
                         */
                        selectionKey.cancel();
                        executorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                                    StringBuilder messageBuilder = new StringBuilder();
                                    int read = socketChannel.read(byteBuffer);
                                    while (read > 0) {
                                        byteBuffer.flip();
                                        messageBuilder.append(new String(byteBuffer.array(), 0, read));
                                        byteBuffer.clear();
                                        read = socketChannel.read(byteBuffer);
                                    }
                                    String request = messageBuilder.toString();
                                    LOGGER.info("read: {}", request);

                                    String response = request.toUpperCase();
                                    socketChannel.write(ByteBuffer.wrap(response.getBytes()));
                                    LOGGER.info("write: {}", response);

                                    socketChannel.close();
                                } catch (Exception e) {
                                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                                }
                            }
                        });
                    } else {
                        LOGGER.info("unhandled selection key: {}", selectionKey);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        new Thread(server).start();
    }
}
